// pages/myOrder/myOrder.js
var app = getApp();
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: app.globalData.imageUrl,
    userInfo: '',
    orderTabData: [
      { txt: '全部', tag: '', idenify: 0, current: true },
      { txt: '待付款', tag: 1, idenify: 0, current: false },
      { txt: '待发货', tag: 2, idenify: 0, current: false },
      { txt: '待收货', tag: 3, idenify: 0, current: false },
      { txt: '待评价', tag: 4, idenify: 0, current: false },
      { txt: '全部', tag: '', idenify: 1, current: true },
      { txt: '待买家付款', tag: 1, idenify: 1, current: false },
      { txt: '待发货', tag: 2, idenify: 1, current: false },
      { txt: '已发货', tag: 3, idenify: 1, current: false },
      { txt: '需要评价', tag: 4, idenify: 1, current: false }
    ],
    active:'',
    inputShow: '',
    shopId:'',
    orderData:[],
    hasTab: true,
    orderStatus:'',
    qrcode: true,
    isShop:'',
    idenify:0,
    paymentCode:'',
    backup:'',
    value:'',
    flowId:'',
    page: 1,
    isShopList: false,
    iden: 0,
    idenShow: false,
    overauthority: false,
    loadSuccess: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading()
    if (wx.getStorageSync('iden')){
      this.setData({
        iden: wx.getStorageSync('iden')
      })
    }
    this.setData({
      isShop: wx.getStorageSync('isShop'),
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })
    if (wx.getStorageSync("isShop") == 1) {
      this.setData({
        shopId: wx.getStorageSync('ShopId')
      })
    }
    if (options.status == 4) {
      this.data.orderTabData.forEach(function (ele) {
        ele.current = false;
      })
      this.data.orderTabData[3].current = true;
      this.setData({
        orderStatus: 4,
        orderTabData: this.data.orderTabData
      })
    }
    if(options.type == 'none'){
      this.setData({
        idenify:1,
        hasTab: false,
        isShopList: true
      })
      this.getShopList();
      wx.setNavigationBarTitle({ title: '待收款' })
    }
    else{
      this.setData({
        isShopList: false
      })
      if (this.data.iden == 1) {
        if (this.data.isShop != 1) {
          this.setData({
            overauthority: true
          })
        }
        else{
          this.setData({
            overauthority: false
          })
          this.getShopList();
        }
      }
      else {
        this.setData({
          overauthority: false
        })
        this.getMyOrder()
      }
    }
    
  },
  changeIdenFunc: function(){
    this.setData({
      idenShow: true
    })
  },
  // 投诉
  complain: function(e){
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/complaint/complaint?userId='+id
    })
  },
  modalhide: function(){
    this.setData({
      idenShow: false
    })
  },
  selectIden: function(e){
    var iden =  e.currentTarget.dataset.iden;
    wx.setStorageSync('iden', iden);
    this.data.orderTabData.forEach(function (ele) {
      ele.current = false;
    })
    this.setData({
      orderStatus: '',
      iden: iden
    })
    if (this.data.iden == 1) {
      if(this.data.isShop != 1){
        this.setData({
          overauthority: true,
          orderData: []
        })
      }
      else{
        this.setData({
          overauthority: false
        })
        this.data.orderTabData[5].current = true;
        this.getShopList();
      }
    }
    else {
      this.setData({
        overauthority: false
      })
      this.data.orderTabData[0].current = true;
      this.getMyOrder()
    }
    this.setData({
      orderTabData: this.data.orderTabData
    })
    this.modalhide()
  },
  // 填写运单号
  inputFunc: function (e) {
    this.setData({
      active: 'active',
      value: e.detail.value
    })
  },
  // 填写运单号模态框
  inputFlow: function(e){
    this.setData({
      flowId: e.currentTarget.dataset.id,
      shopId: e.currentTarget.dataset.shopid,
      inputShow: true
    })
  },
  // 提交订单号
  bindFormSubmit: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'orderLogistics/save',
      data: {
        backupB: _this.data.flowId,
        shopId: _this.data.shopId,
        logNum: _this.data.value
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      success: function (res) {
        _this.setData({
          orderStatus: 2,
          inputShow: false
        })
        _this.getShopList();
      }
    });
  },
  // 查询店铺订单
  getShopList: function(){
    if (!this.data.overauthority){
      var _this = this;
      _this.setData({
        orderData: []
      })
      var arr = (_this.data.orderStatus + "").split(",");
      for (var i = 0; i < arr.length; i++) {
        wx.request({
          url: app.globalData.httpApiCar + 'shopOrder/all',
          data: {
            orderStatus: arr[i],
            shopId: _this.data.shopId,
            userpay: 2
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function (res) {
            _this.setData({
              loadSuccess: true
            })
            wx.hideLoading()
            var result = res.data.data;
            var obj = {};
            var shopNum = 0;
            var shopMoney = 0;
            wx.hideNavigationBarLoading() //完成停止加载
            wx.stopPullDownRefresh() //停止下拉刷新
            for (var j = 0; j < result.length; j++) {
              if (obj[result[j].backupB]) {
                if (result[j].shopThing){
                  result[j].shopThing.realThingShowImg = result[j].shopThing.realThingShowImg.split(",");
                }
                obj[result[j].backupB].push(result[j]);
              } else {
                obj[result[j].backupB] = [];
                if (result[j].shopThing) {
                  result[j].shopThing.realThingShowImg = result[j].shopThing.realThingShowImg.split(",");
                }
                obj[result[j].backupB].push(result[j])
              }
            }
            var arr = [];
            for (var key in obj) {
              let obj1 = {};
              obj1.backupB = key;
              var shopNum = 0;
              var shopMoney = 0;
              for (var t = 0; t < obj[key].length; t++) {
                shopNum += parseInt(obj[key][t].amount);
                shopMoney += (parseInt(obj[key][t].amount) * obj[key][t].price);
              }
              obj1.shopNum = shopNum;
              obj1.shopMoney = shopMoney + obj[key][0].youFei;
              obj1.wareList = obj[key];
              arr.push(obj1);
            }
            for (var t = 0; t < arr.length; t++) {
              _this.data.orderData.push(arr[t])
            }
            _this.setData({
              orderData: _this.data.orderData
            })
          }
        })
      }
    }
  },
  swichTab:function(e){
    if(!this.data.overauthority){
      let flag = e.currentTarget.dataset.flag;
      this.data.orderTabData.forEach(function (ele) {
        ele.current = false;
      })
      this.data.orderTabData[e.currentTarget.dataset.value].current = true;
      this.setData({
        idenify: flag,
        orderStatus: e.currentTarget.dataset.tag,
        orderTabData: this.data.orderTabData
      })
      if (flag == 1) {
        this.getShopList();
      }
      else {
        this.getMyOrder()
      }
    }
  },
  // 去买单
  pay: function (e) {
    var item = e.currentTarget.dataset.item;
    console.info(item)
    this.payMoney(item.shopMoney, item.backupB,item.wareList.shopInfo.id)
  },
  payMoney: function (money, backupB) {
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/payTheBill',
      data: {
        openId: app.globalData.openId,
        backupB: backupB,
        backupE: backupE,
        backupC: 6,
        userId: that.data.userInfo.id,
        money: money,
        body: '购买商品支付费用'
      },
      success: function (res) {
        if (res.data.success) {
          that.requestPayment(res.data.data, backupB,money);
        }
      }
    })
  },
  requestPayment: function (obj, backupB, money) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        that.getMoney(2, backupB, money)
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            that.getMoney(1, backupB, money)
            if (res.confirm) {
            }
          }
        })
      }
    })
  },
  // 改变订单状态
  changeStatus: function(e){
    var _this = this;
    let id = e.currentTarget.dataset.id;
    let status = e.currentTarget.dataset.status;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/update',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      data: {
        backupB: id,
        orderStatus: status
      },
      success: function (res) {
        if (_this.data.idenify == 1) {
          _this.getShopList();
        }
        else {
          _this.getMyOrder()
        }
      }
    })
  },
  // 确认收款
  getMoney(status, backupB,money){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/update',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      data: {
        backupB: backupB,
        shopPay: 2,
        orderStatus: status
      },
      success: function (res) {
        if(res.data.success){
          _this.getShopList();
          _this.moneyList(money,1)
        }
      }
    })
  },
  // 交易记录
  moneyList: function(money,adds){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'userPayInfo/save',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      data: {
        userId: _this.data.userInfo.id,
        adds: adds,
        money: money
      },
      success: function (res) {
        
      }
    })
  },
  // 物流
  getFlow: function(e){
    let numbers = e.currentTarget.dataset.number;  // 3804532311307
    wx.navigateTo({
      url: '/pages/logistics/logistics?number='+numbers,
    })
  },
  // 评价
  discuss: function (e) {
    let item = e.currentTarget.dataset.item; 
    let id = e.currentTarget.dataset.id; 
    let backup = e.currentTarget.dataset.backup; 
    wx.navigateTo({
      url: '/pages/evaluate/evaluate?id=' + id + '&backup=' + backup + '&item=' + JSON.stringify(item),
    })
  },
  // 取消
  codeCancel: function () {
    this.setData({
      qrcode: true
    })
  },
  // 确定
  codeConfirm: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/update',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      data: {
        backupB: _this.data.backup,
        userPay: 2
      },
      success: function (res) {
        if(res.data.success){
          _this.codeCancel();
          _this.getMyOrder();
          _this.moneyList(e.currentTarget.dataset.item.shopMoney, 2)
        }
        else{
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 查询我的订单信息
  getMyOrder: function (){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/all',
      data: {
        orderStatus: _this.data.orderStatus,
        userId: _this.data.userInfo.id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        _this.setData({
          loadSuccess: true
        })
        wx.hideLoading()
        var result = res.data.data;
        var obj = {};
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
        for (var j = 0; j < result.length; j++){
          let shopBuyNum = 0; 
          if (obj[result[j].backupB]) {
            if (result[j].shopThing){
              result[j].shopThing.realThingShowImg = result[j].shopThing.realThingShowImg.split(",");
            }
            obj[result[j].backupB].push(result[j]);
          } else {
            obj[result[j].backupB] = [];
            if (result[j].shopThing){
              result[j].shopThing.realThingShowImg = result[j].shopThing.realThingShowImg.split(",");
            }
            obj[result[j].backupB].push(result[j])
          }
        }
        var arr = [];
        for (var key in obj) {
          let obj1 = {};
          obj1.backupB = key;
          var shopNum = 0;
          var shopMoney = 0;
          for (var t = 0; t < obj[key].length; t++) {
            shopNum += parseInt(obj[key][t].amount);
            shopMoney += (parseInt(obj[key][t].amount) * obj[key][t].price);
          }
          obj1.shopNum = shopNum;
          obj1.shopMoney = shopMoney + obj[key][0].youFei;
          obj1.wareList = obj[key];
          arr.push(obj1);
        }
        _this.setData({
          orderData: arr
        })
      }
    })
  },
  // 删除订单
  delOrder: function(e){
    var id = e.currentTarget.dataset.id;
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/del',
      data: {
        id: id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST',
      success: function (res) {
        if(res.data.success){
          if (_this.data.iden == 1) {
            _this.getShopList();
          }
          else {
            _this.getMyOrder()
          }
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading(); //在标题栏中显示加载
    this.setData({
      loadSuccess: false
    })
    if (this.data.iden == 1){
      this.getShopList();
    }
    else {
      this.getMyOrder();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})